﻿using System;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using RHD.Common.Web.Components.Tab;
using RHD.Web.Infrastructure;

namespace RHD.Common.Web.Components {
	public static class TabExtension {
		public static MvcHtmlString Tab(this HtmlHelper htmlHelper, string id, Action<TabItems> itemsHandle, Action<TabBuilder> optionsHandle = null, object htmlAttributes = null) {
			TabItems items = new TabItems();
			if (itemsHandle != null)
				itemsHandle(items);

			TabBuilder options = new TabBuilder();
			if (optionsHandle != null)
				optionsHandle(options);

			TagBuilder div = GetTab(id, items, options);
			div.GenerateId(id);
			if (htmlAttributes != null)
				div.MergeAttributes<string, object>(new RouteValueDictionary(htmlAttributes));

			return MvcHtmlString.Create(div.ToString());
		}

		private static TagBuilder GetTab(string id, TabItems items, TabBuilder options) {
			TagBuilder tab = new TagBuilder("div");

			TagBuilder ul = new TagBuilder("ul");
			ul.AddCssClass(string.Format("nav nav-{0}", options.type.ToString().ToLower()));

			TagBuilder content = new TagBuilder("div");
			content.AddCssClass("tab-content");

			int i = 1;
			foreach (TabItemBuilder item in items.GetItems()) {
				TagBuilder li = new TagBuilder("li");
				if (i == 1)
					li.AddCssClass("active");

				TagBuilder a = new TagBuilder("a");
				a.SetInnerText(item.label);
				a.Attributes["href"] = string.Format("#{0}", id + "_" + i);
				a.Attributes["data-toggle"] = "tab";

				li.InnerHtml = a.ToString();
				ul.InnerHtml += li.ToString();

				TagBuilder div = new TagBuilder("div");
				div.GenerateId(id + "_" + i);
				div.AddCssClass("tab-pane");
				if (i == 1)
					div.AddCssClass("active");
				div.SetInnerText(item.html);

				content.InnerHtml += div.ToString();

				i++;
			}

			tab.InnerHtml = ul.ToString() + content.ToString();

			return tab;
		}
	}
}